#include "../source/http/http_connection.h"
#include "../source/io_manager.h"
#include "../source/address.h"
#include "../source/socket.h"
#include "../source/log.h"
#include <fstream>
#include <memory>

void test_connection_pool()
{
    std::ofstream ofs("./test");
    MYHTTP::HttpConnectionPool::ptr pool = std::make_shared<MYHTTP::HttpConnectionPool>(
        "www.sylar.top", "", 80, 10, 1000 * 10, 5, false);
    
    auto r = pool->doGet("/", 3000);
    ofs << r->toString() << std::endl;
    ofs << "\n\n===========================================\n\n" << std::endl;

    sleep(2);

    auto r2 = pool->doGet("/", 3000);
    ofs << r2->toString() << std::endl;
    ofs << "\n\n===========================================\n\n" << std::endl;

    sleep(8);

    auto r3 = pool->doGet("/", 3000);
    ofs << r3->toString() << std::endl;
    ofs << "/n/n===========================================/n/n" << std::endl;

    ofs.close();
    log_debug("file close");
}

//测试分块数据
void run()
{
    Address::ptr addr = Address::LookupAny("www.sylar.top:80");
    if(!addr)
    {
        log_error("LookupAny failed");
        return;
    }
    Socket::ptr socket = Socket::CreateTCP(addr);
    bool rt = socket->connect(addr);
    if(!rt)
    {
        log_error("Connect failed");
        return;
    }
    log_debug("local ip:{}", socket->getLocalAddress()->toString());

    MYHTTP::HttpConnection::ptr conn = std::make_shared<MYHTTP::HttpConnection>(socket);  
    MYHTTP::HttpRequest::ptr req = std::make_shared<MYHTTP::HttpRequest>();
    req->setHeader("host", "www.sylar.top");
    req->setPath("/blog/");
    conn->sendRequest(req);
    auto rsp = conn->recvResponse();
    if(!rsp)
    {
        log_error("recvResponse failed");
        return;
    }
    // log_debug("rsp:\n{}", rsp->toString());
    std::ofstream ofs("./test");
    ofs << rsp->toString() << std::endl;
    ofs.close();
}

void test_HttpResult()
{
    auto r = MYHTTP::HttpConnection::DoGet("http://www.sylar.top/blog/", 3000);
    std::cout << r->toString() << std::endl;
}

int main(void)
{
    IOManager iom(2);
    // iom.schedule(run);
    // iom.schedule(test_HttpResult);
    iom.schedule(test_connection_pool);
    

    return 0;
}